
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Api;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Utility.Helper;
using Flurl.Http;
using Newtonsoft.Json;
using SqlSugar.Extensions;


namespace CoreCms.Net.Services
{
    /// <summary>
    /// 物流公司表 接口实现
    /// </summary>
    public class CoreCmsLogisticsServices : BaseServices<CoreCmsLogistics>, ICoreCmsLogisticsServices
    {
        private readonly ICoreCmsLogisticsRepository _dal;
        private readonly ICoreCmsSettingServices _settingServices;
        private readonly IUnitOfWork _unitOfWork;



        public CoreCmsLogisticsServices(IUnitOfWork unitOfWork, ICoreCmsLogisticsRepository dal, ICoreCmsSettingServices settingServices)
        {
            this._dal = dal;
            _settingServices = settingServices;
            base.BaseDal = dal;
            _unitOfWork = unitOfWork;
        }



        /// <summary>
        /// 根据物流编码取物流名称等信息
        /// </summary>
        /// <param name="logiCode">物流编码</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetLogiInfo(string logiCode)
        {
            var jm = new WebApiCallBack();

            var model = await _dal.QueryByClauseAsync(p => p.logiCode == logiCode);
            jm.status = model != null;
            jm.data = model;
            jm.msg = jm.status ? GlobalConstVars.GetDataSuccess : GlobalConstVars.GetDataFailure;

            return jm;
        }


        /// <summary>
        /// 通过接口更新所有快递公司信息
        /// </summary>
        public async Task<AdminUiCallBack> DoUpdateCompany()
        {
            var jm = new AdminUiCallBack();

            var allConfigs = await _settingServices.GetConfigDictionaries();
            var showApiLogisticsVersion = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShowApiLogisticsVersion).ObjToInt(1);
            var showApiAppid = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShowApiAppid);
            var showApiSecret = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShowApiSecret);
            var shopMobile = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShopMobile);

            var showApiTimesTamp = DateTime.Now.ToString("yyyyMMddHHmmss");

            var maxSize = 1500;
            var signStr = "maxSize" + maxSize + "showapi_appid" + showApiAppid + "showapi_timestamp" + showApiTimesTamp + showApiSecret;
            var md5Sign = CommonHelper.Md5For32(signStr).ToLower();

            string url;
            if (showApiLogisticsVersion == 1)
            {
                url = "https://route.showapi.com/64-20?expName=&maxSize=1500&page=&showapi_appid=" + showApiAppid + "&showapi_timestamp=" + showApiTimesTamp + "&showapi_sign=" + md5Sign;

                var result = await url.PostAsync().ReceiveJson<ShowApiGetExpressCompanyListResultV1>();

                if (result.showapi_res_code == 0)
                {
                    if (result.showapi_res_body != null && result.showapi_res_body.ret_code == 0 && result.showapi_res_body.expressList != null && result.showapi_res_body.expressList.Count > 0)
                    {
                        var list = new List<CoreCmsLogistics>();

                        var systemLogistics = SystemSettingDictionary.GetSystemLogistics();
                        systemLogistics.ForEach(p =>
                        {
                            var logistics = new CoreCmsLogistics();
                            logistics.logiCode = p.sKey;
                            logistics.logiName = p.sDescription;
                            logistics.imgUrl = "";
                            logistics.phone = shopMobile;
                            logistics.url = "";
                            logistics.sort = -1;
                            logistics.isDelete = false;

                            list.Add(logistics);
                        });

                        var count = 0;
                        result.showapi_res_body.expressList.ForEach(p =>
                        {
                            var logistics = new CoreCmsLogistics();
                            logistics.logiCode = p.simpleName;
                            logistics.logiName = p.expName;
                            logistics.imgUrl = p.imgUrl;
                            logistics.phone = p.phone;
                            logistics.url = p.url;
                            logistics.sort = count * 5;
                            logistics.isDelete = false;

                            list.Add(logistics);
                            count++;
                        });
                        await _dal.DeleteAsync(p => p.id > 0);
                        var bl = await _dal.InsertAsync(list) > 0;
                        jm.code = bl ? 0 : 1;
                        jm.msg = bl ? "数据刷新成功" : "数据刷新失败";
                    }
                    else
                    {
                        jm.msg = "接口获取数据失败";
                    }
                }
                else
                {
                    jm.msg = result.showapi_res_error;
                }
            }
            else
            {
                url = "https://route.showapi.com/2650-5?expName=&maxSize=1500&page=&showapi_appid=" + showApiAppid + "&showapi_timestamp=" + showApiTimesTamp + "&showapi_sign=" + md5Sign;

                var result = await url.PostAsync().ReceiveJson<ShowApiGetExpressCompanyListResultV2>();

                if (result.showapi_res_code == 0)
                {
                    if (result.showapi_res_body != null && result.showapi_res_body.ret_code == 0 && result.showapi_res_body.express_list != null && result.showapi_res_body.express_list.Count > 0)
                    {
                        var list = new List<CoreCmsLogistics>();

                        var systemLogistics = SystemSettingDictionary.GetSystemLogistics();
                        systemLogistics.ForEach(p =>
                        {
                            var logistics = new CoreCmsLogistics();
                            logistics.logiCode = p.sKey;
                            logistics.logiName = p.sDescription;
                            logistics.imgUrl = "";
                            logistics.phone = shopMobile;
                            logistics.url = "";
                            logistics.sort = -1;
                            logistics.isDelete = false;

                            list.Add(logistics);
                        });

                        var count = 0;
                        result.showapi_res_body.express_list.ForEach(p =>
                        {
                            var logistics = new CoreCmsLogistics();
                            logistics.logiCode = p.com;
                            logistics.logiName = p.exp_name;
                            logistics.imgUrl = p.img_url;
                            logistics.phone = p.phone;
                            logistics.url = p.url;
                            logistics.sort = count * 5;
                            logistics.isDelete = false;

                            list.Add(logistics);
                            count++;
                        });
                        await _dal.DeleteAsync(p => p.id > 0);
                        var bl = await _dal.InsertAsync(list) > 0;
                        jm.code = bl ? 0 : 1;
                        jm.msg = bl ? "数据刷新成功" : "数据刷新失败";
                    }
                    else
                    {
                        jm.msg = "接口获取数据失败";
                    }
                }
                else
                {
                    jm.msg = result.showapi_res_error;
                }
            }


            return jm;
        }


        /// <summary>
        /// 通过接口获取快递信息
        /// </summary>
        /// <param name="com">来源</param>
        /// <param name="number">编号</param>
        /// <param name="phone">手机号码</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> ExpressPoll(string com, string number, string phone)
        {
            var jm = new WebApiCallBack();


            if (string.IsNullOrEmpty(com))
            {
                jm.msg = "请提交来源";
                return jm;
            }
            else if (string.IsNullOrEmpty(number))
            {
                jm.msg = "请提交编号";
                return jm;
            }
            else if (string.IsNullOrEmpty(phone))
            {
                jm.msg = "请提交手机号码";
                return jm;
            }

            var allConfigs = await _settingServices.GetConfigDictionaries();
            var showApiLogisticsVersion = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShowApiLogisticsVersion).ObjToInt(1);
            var showApiAppid = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShowApiAppid);
            var showApiSecret = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShowApiSecret);

            var showApiTimesTamp = DateTime.Now.ToString("yyyyMMddHHmmss");

            var signStr = "com" + com + "nu" + number + "phone" + phone + "showapi_appid" + showApiAppid + "showapi_timestamp" + showApiTimesTamp + showApiSecret;
            var md5Sign = CommonHelper.Md5For32(signStr).ToLower();

            string url;
            if (showApiLogisticsVersion == 1)
            {
                url = "https://route.showapi.com/64-19?com=" + com + "&nu=" + number + "&phone=" + phone + "&showapi_appid=" + showApiAppid + "&showapi_timestamp=" + showApiTimesTamp + "&showapi_sign=" + md5Sign;
                var result = await url.PostAsync().ReceiveJson<ShowApiGetExpressPollResultV1>();
                if (result.showapi_res_code != 0)
                {
                    jm.status = false;
                    jm.msg = result.showapi_res_error;
                }
                else
                {
                    jm = GetLogiInfo(1, result.showapi_res_code, result.showapi_res_body);
                }
            }
            else
            {
                url = "https://route.showapi.com/2650-3?com=" + com + "&nu=" + number + "&phone=" + phone + "&showapi_appid=" + showApiAppid + "&showapi_timestamp=" + showApiTimesTamp + "&showapi_sign=" + md5Sign;
                var result = await url.PostAsync().ReceiveJson<ShowApiGetExpressPollResultV2>();
                if (result.showapi_res_code != 0)
                {
                    jm.status = false;
                    jm.msg = result.showapi_res_error;
                }
                else
                {
                    jm = GetLogiInfo(1, result.showapi_res_code, result.showapi_res_body);
                }
            }
            return jm;
        }

        //根据状态反馈提示信息
        private WebApiCallBack GetLogiInfo(int version, int retCode, object showapiResBody)
        {
            var jm = new WebApiCallBack();

            if (retCode == 0)
            {
                jm.status = true;
                jm.msg = "查询成功";
                jm.data = showapiResBody;
            }
            else if (retCode == 1)
            {
                jm.status = false;
                jm.msg = "输入参数错误";
                jm.data = showapiResBody;
            }
            else if (retCode == 2)
            {
                jm.status = false;
                jm.msg = "查不到物流信息";
                jm.data = showapiResBody;
            }
            else if (retCode == 3)
            {
                jm.status = false;
                jm.msg = "单号不符合规则";
                jm.data = showapiResBody;
            }
            else if (retCode == 4)
            {
                jm.status = false;
                jm.msg = "快递公司编码不符合规则";
                jm.data = showapiResBody;
            }
            else if (retCode == 5)
            {
                jm.status = false;
                jm.msg = "快递查询渠道异常";
                jm.data = showapiResBody;
            }
            else if (retCode == 6)
            {
                jm.status = false;
                jm.msg = " auto时未查到单号对应的快递公司,请指定快递公司编码";
                jm.data = showapiResBody;
            }
            else if (retCode == 7)
            {
                jm.status = false;
                jm.msg = "单号与手机号不匹配";
                jm.data = showapiResBody;
            }
            else if (version == 2)
            {
                jm.status = true;

                switch (retCode)
                {
                    //101 揽件
                    //102 在途中
                    //103 派送中
                    //104 已签收(完结状态)
                    //105 用户拒签
                    //106 疑难件
                    //107 无效单(完结状态)
                    //108 超时单
                    //109 签收失败
                    //110 退回
                    //111 转投
                    //112 待签
                    //113 邮件回收
                    case 101:
                        jm.msg = "揽件";
                        break;
                    case 102:
                        jm.msg = "在途中";
                        break;
                    case 103:
                        jm.msg = "派送中";
                        break;
                    case 104:
                        jm.msg = "已签收(完结状态)";
                        break;
                    case 105:
                        jm.msg = "用户拒签";
                        break;
                    case 106:
                        jm.msg = "疑难件";
                        break;
                    case 107:
                        jm.msg = "无效单(完结状态)";
                        break;
                    case 108:
                        jm.msg = "超时单";
                        break;
                    case 109:
                        jm.msg = "签收失败";
                        break;
                    case 110:
                        jm.msg = "退回";
                        break;
                    case 111:
                        jm.msg = "转投";
                        break;
                    case 112:
                        jm.msg = "待签";
                        break;
                    case 113:
                        jm.msg = "邮件回收";
                        break;
                    default:
                        jm.status = false;
                        jm.msg = "未知状态";
                        break;
                }
                jm.data = showapiResBody;
            }
            else
            {
                jm.status = false;
                jm.msg = "接口调用失败";
                jm.data = showapiResBody;
            }

            return jm;
        }

    }
}
